$(() => {    
  // 监听消息传递
  chrome.extension.onMessage.addListener(
    function (req, sender, res) {
      if (req.action === 'completed') {
        //页面加载完毕
        if (/^https:\/\/detail\.1688\.com\/offer\/\d+\.html/.test(req.url)) {
          $('html,body').animate({ scrollTop: document.body.scrollHeight }, 1000)
          setTimeout(() => {
            getDetail(req)
          }, 1000)
        }else if (/^https:\/\/.+\.1688\.com\/page\/offerlist.*\.htm/.test(req.url)) {
          window.scrollTo(0, document.body.scrollHeight)
          getList(req, res)
        }
      }
      // 一定要 return
      return true
    }
  )
})


// 获取商品列表以及sku
function getList() {
  var list = $(".wp-offerlist-windows.should-get-async-price .offer-list-row .offer-list-row-offer")
  let  productList = []
  if (/^https:\/\/.+\.1688\.com\/page\/offerlist.*\.htm.*/.test(location.href)  && list && list.length > 0) {
    // 排列数据
    list.each(function () {
      productList.push([{ id: '1688_' + $(this).attr('data-offerid'), url: $(this).find('.image a').attr('href') }])
    })
    // 判断是否有分页组件 没有则end
    let pagination = $('.app-paginator .pagination a')
    if (pagination && pagination.length > 0) {
      if ($('.app-paginator .pagination a:last-child').attr('class') === 'next-disabled') {
        // 最后一页
        sendMsg({ data: productList }, 'end')
      } else {
        sendMsg({ data: productList, url: $('.app-paginator .pagination a[class=current] + a').attr('href') }, 'next')
      }
    } else {
      sendMsg({ data: productList }, 'end')
    }
  } else {
    console.log('not found')
   // alert("No data")
  }
}

var detailInfo = new Object()

// 获取sku数据
function getDetail() {
  if (/^https:\/\/detail\.1688\.com\/offer\/\d+\.html.*/.test(location.href)) {
    // 报价方式
    console.log('获取商品详情')
    if ($('.offerdetail_ditto_purchasing .mod-detail-purchasing .obj-sku').length > 0) {
      // 按规格报价
      detailInfo.quoteMode = 'SPECIFICATIONS'
      detailInfo.specifications = []
      detailInfo.productSpecifications = []

      // 有颜色规格
      let leadingList = $('.offerdetail_ditto_purchasing .mod-detail-purchasing .obj-leading .obj-content ul[class=list-leading]>li')
      let skuList = $('.offerdetail_ditto_purchasing .mod-detail-purchasing .obj-sku .table-sku tr')
      let colorValues = [], sizeValue = []
      if (leadingList.length > 0) {
        leadingList.each(function() {
          let skuData = []
          let colorNode = $(this).find('.unit-detail-spec-operator')
          colorValues.push({
            icon: colorNode.attr('data-imgs') ? JSON.parse(colorNode.attr('data-imgs')).preview.replace('400x400', '32x32') : '',
            value: JSON.parse(colorNode.attr('data-unit-config')).name
          })

          // 颜色具体的规格列表 二维数组
          $(this).find('a').attr('class', 'image selected')
          $(this).siblings().find('a').attr('class', 'image')
          let values = []
          skuList.each(function() {
            let name0 = JSON.parse(colorNode.attr('data-unit-config')).name
            let name1 = JSON.parse($(this).attr('data-sku-config')).skuName
            skuData.push({
              distributionAmount: 0,
              inventory: $(this).find('td[class=count] .value').text(),
              sellingPrice: $(this).find('td[class=price] .value').text(),
              value: `${name0},${name1}`,
              names: [name0, name1],
              name0: name0,
              name1: name1
            })
            values.push({
              icon: '',
              value: name1
            })
          })
          sizeValue = values
          detailInfo.productSpecifications.push(...skuData)
        })
        detailInfo.specifications = detailInfo.specifications.concat({
          name: $('.offerdetail_ditto_purchasing .mod-detail-purchasing .obj-leading .obj-header .obj-title').text(),
          values: colorValues
        }, {
          name: $('.offerdetail_ditto_purchasing .mod-detail-purchasing .obj-sku .obj-header .obj-title').text(),
          values: sizeValue
        })
      } else if (skuList.length > 0) {
        sizeValue = []
        // 只有尺寸规格
        skuList.each(function() {
          let skuConfig = JSON.parse($(this).attr('data-sku-config'))
          let productData = {
            distributionAmount: 0,
            inventory: skuConfig.max,
            sellingPrice: $(this).find('td[class=price] .value').text(),
            value: skuConfig.skuName,
            names: [skuConfig.skuName],
            name0: skuConfig.skuName
          }
          sizeValue.push({
            icon: '',
            value: skuConfig.skuName
          })
          detailInfo.productSpecifications.push(productData)
        })
        detailInfo.specifications = detailInfo.specifications.concat({
          name: $('.offerdetail_ditto_purchasing .mod-detail-purchasing .obj-sku .obj-header .obj-title').text(),
          values: sizeValue
        })
      }
    } else if ($('#mod-detail-price table tr[class=price] td').length > 0) {
      // 按数量报价
      const configObj = $('.offerdetail_ditto_purchasing .mod-detail-purchasing').attr('data-mod-config')
      let config = configObj ? JSON.parse(configObj) : {}
      detailInfo.quoteMode = 'NUMBERS'
      let numbersQuotes = []
      let batchPrice = $('#mod-detail-price table tr[class=price] td')
      batchPrice.each(function() {
        let amountConfig = $(this).attr('data-range')
        if (amountConfig) {
          numbersQuotes.push({
            startNumber: JSON.parse(amountConfig).begin,
            price: JSON.parse(amountConfig).price
          })
        } else if ($(this).find('.price-original-sku .value').text()) {
          numbersQuotes.push({
            startNumber: $('#mod-detail-price tr[class=amount] .value').text().replace(/[^0-9]/ig, ''),
            price: $(this).find('.price-original-sku .value').text().replace(/[^0-9]/ig, '')
          })
        }
      })
      
      detailInfo.numbersQuote = {
        inventory: config.max,
        numbersQuotes: numbersQuotes
      }
    }

    // 设置最小起定量/重量
    try {
      let minWeightObj = JSON.parse($('.unit-detail-freight-cost').attr('data-unit-config'))
      detailInfo.minQuantity = minWeightObj.beginAmount
      detailInfo.weight = minWeightObj.unitWeight
    }
    catch(error) {
      detailInfo.minQuantity = null
      detailInfo.weight = 1
    }
    
    // 设置主图
    let imageNode = $('#dt-tab .tab-content-container ul>li')
    detailInfo.images = []
    imageNode.each(function(index) {
      let imageObj
      if ($(this).attr('data-imgs')) {
        imageObj = JSON.parse($(this).attr('data-imgs')).preview
      } else if ($(this).attr('class').indexOf('tab-gallery-main-video') !== -1) {
        imageObj = $(this).find('img').attr('src')
      }
      if (index < 5 && imageObj) {
        detailInfo.images.push({
          imageURL: imageObj,
          isMain: index === 0,
          sort: index,
          streamMediaType: 'IMG'
        })
      }
    })

    // 快递费
    try {
      let fare = $('.offerdetail_ditto_postage .d-content .obj-carriage .unit-detail-freight-cost .cost-entries-type p:nth-child(2) .value').text()
      detailInfo.fareStyle = parseFloat(fare) > 0 ? 'FIXED' : 'FREE'
      detailInfo.fareFee = parseFloat(fare)
    }
    catch (error) {
      detailInfo.fareStyle = 'FREE'
    }

    // 单位
    detailInfo.productUnit = $('#mod-detail-price .amount td:nth-child(2) .unit').text()

    // 标题
    detailInfo.title = $('#mod-detail-title .d-title').text()

    // 品牌/商品规格详情介绍
    let productInfoNodes = $('#mod-detail-attributes .obj-content tr')
    let parameterList = []
    productInfoNodes.each(function() {
      $(this).find('td').each(function() {
        if ($(this).text().indexOf('品牌') !== -1) {
          detailInfo.brand = $(this).next().text()
        }
      })
      let title = $(this).find('td[class=de-feature]')
      let value = $(this).find('td[class=de-value]')
      title.each(function(index) {
        parameterList.push($(this).text() + '：' + $(value[index]).text())
      })
    })
    let productSourceInfo = {
      url:location.href,
      title: detailInfo.title,
      name: '商品信息',
      props: parameterList,
      specs: []
    }
    detailInfo.productSourceInfo = productSourceInfo

    // 来源
    detailInfo.productSourceType = '3'

    // 详情图片
    let timer = setInterval(function() {
      if ($('#desc-lazyload-container').text() !== '加载中...') {
        //删除 超链接 模块
        if (checkLazyImage()) {
          $('#desc-lazyload-container table').each(function() {
            if ($(this).find('a[target="_blank"]').length > 0) {
              $(this).remove()
            }
          })
          detailInfo.info = $('#desc-lazyload-container').html()
          sendMsg(detailInfo, 'upload')
          clearInterval(timer)
        } else {
          $('html,body').animate({ scrollTop: document.body.scrollHeight }, 100)
        }
      }
    },1000)
  }
}

function checkLazyImage() {
  let flag = true
  $('#desc-lazyload-container img').each(function(e) {
    if ($(this).attr('data-lazyload-src')) {
      flag = false
    }
  })
  return flag
}


// 将获取内容传递给后台脚本进行处理
function sendMsg(msg, cmd) {
　　chrome.extension.sendMessage({ 'msg': msg, 'cmd': cmd })
}
